﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pavilion.DesignerTool
{
    public class TrackedLink
    {
        private Link link;
        private ContainerNode parentContainer;
        private NodeScript parentNodeScript;
        private ResourceItem parentResource;

        private List<ILock> originalLockWrapperList;
        private List<TrackedLock> trackedLockCollection;
        private OpenCriteria originalCriteria;

        public TrackedLink(Link link, ContainerNode parentContainer, NodeScript parentNodeScript, ResourceItem parentResource)
        {
            this.link = link;
            this.originalCriteria = link.OpenCriteria;
            this.parentContainer = parentContainer;
            this.parentNodeScript = parentNodeScript;
            this.parentResource = parentResource;

            originalLockWrapperList = new List<ILock>(link.LockCollection);
            trackedLockCollection = new List<TrackedLock>();

            foreach (ILock item in link.LockCollection)
                trackedLockCollection.Add(new TrackedLock(parentResource, parentNodeScript, parentContainer, link, item));
        }

        public void TransferData()
        {
            if (originalCriteria != link.OpenCriteria)
                LinkTransfer.UpdateOpenCriteria(parentResource.Name, parentNodeScript.Name, parentContainer, link);

            CollectionDelta<ILock> lockCollectionDelta = new CollectionDelta<ILock>(originalLockWrapperList, link.LockCollection);

            List<ILock> copyOfOriginal = new List<ILock>(originalLockWrapperList);
            foreach (ILock deletedLock in lockCollectionDelta.DeletedItems)
            {
                int lockIndex = copyOfOriginal.IndexOf(deletedLock);
                LockTransfer.Remove(parentResource.Name, parentNodeScript.Name, parentContainer, link, lockIndex);
                copyOfOriginal.RemoveAt(lockIndex);
            }

            foreach (ILock newLock in lockCollectionDelta.NewItems)
                LockTransfer.Add(parentResource.Name, parentNodeScript.Name, parentContainer, link, newLock);

            foreach (TrackedLock trackedLock in trackedLockCollection)
                trackedLock.TransferData();
        }
    }
}
